package com.yuwj.chinaa.view;

import android.app.Dialog;
import android.content.DialogInterface;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.view.Display;
import android.view.WindowManager;

import com.yuwj.chinaa.callback.BankNameSelectCallback;
import com.yuwj.chinaa.util.ToastUtil;

/**
 * 选择银行名称对话框
 */

public class SelectBankNameDialog {
    FragmentActivity activity;
    Dialog dialog;//弹出的对话框
    String[] items;//列表项
    BankNameSelectCallback bankNameSelectCallback;//item选中回调

    public SelectBankNameDialog(FragmentActivity activity, String[] items, BankNameSelectCallback bankNameSelectCallback) {
        this.activity = activity;
        this.items = items;
        this.bankNameSelectCallback = bankNameSelectCallback;
    }

    public void showDialog() {
        if (dialog == null) {
            final int[] selectedIndex = {-1};
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setTitle("请选择银行名称");
            //由于message 和 items 都属于弹出框的内容部分,两者只能显示一个, 所以千万不要加这句，不然列表显示不出来
            //builder.setMessage("这是一个简单的列表对话框");
            //builder.setIcon(R.mipmap.ic_launcher);
            builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    selectedIndex[0] = which;
                }
            });

            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    int index = selectedIndex[0];
                    if (index < 0) {
                        index = 0;
                    }
                    if (items.length > 0) {
                        String reason = items[index];
                        bankNameSelectCallback.onBankNameSelectSuccess(reason);
                    } else {
                        ToastUtil.getInstance().shortLength(activity, "未选择银行名称");
                    }
                }
            }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });

            dialog = builder.create();
            dialog.show();
            // 将对话框的大小按屏幕大小的百分比设置
            WindowManager windowManager = dialog.getWindow().getWindowManager();
            Display display = windowManager.getDefaultDisplay();
            WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
            lp.width = (int) (display.getWidth() * 1); //设置宽度
            lp.height = (int) (display.getHeight() * 0.7); //设置高度
            dialog.getWindow().setAttributes(lp);
        } else {
            dialog.show();
        }
    }
}
